package com.neighbor.neighborhooduser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neighbor.neighborhooduser.pojo.Notifications;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.service.INotificationsService;
import com.neighbor.neighborhooduser.utils.RedisUtils;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统通知表 前端控制器
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@RestController
//@RequestMapping("/notifications")
public class NotificationsController {

    @Autowired
    private INotificationsService notificationsService;

    @Autowired
    RedisUtils redisUtils;


    /**
     * 获取最新系统公告
     * @return ResponseMsg
     */
    @GetMapping("/notice/latest")
    public ResponseMsg latestNotice(){
        Notifications notice = (Notifications) redisUtils.get("neighbor:notice");
        if(notice == null){
            notice = notificationsService.latestNotice();
            redisUtils.set("neighbor:notice",notice,86400);
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS,"获取成功", notice);
    }
    @GetMapping("/notification/list")
    public Map<String, Object> getNotificationList(
            @RequestParam Integer userId,
            @RequestParam(required = false) Integer type,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {

        IPage<Notifications> page = notificationsService.getUserNotifications(userId, type, pageNum, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("data", page.getRecords());
        result.put("total", page.getTotal());
        result.put("pages", page.getPages());
        return result;
    }

    /**
     * 得到单个用户的 所有通知
     * @param userId
     * @return
     */
    @GetMapping("/notification/allNotification/{userId}")
    ResponseMsg getAllNotification(@PathVariable Integer userId){
        List<Notifications> notificationsList = notificationsService.getAllNotification(userId);
        if (notificationsList != null){
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询成功", notificationsList);
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查询结果为空");
    }

    /**
     * 给用户 生成订单通知
     * @param notifications
     * @return
     */
    @RequestMapping("/notification/addOrderNotification")
    ResponseMsg addOrderNotification(@RequestBody Notifications notifications){
        notifications.setCreatedAt(new Date());
        if (notificationsService.save(notifications)){
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "生成订单通知成功", notifications);
        }
        return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "生成订单通知失败");
    }
    @GetMapping("/notification/getOneNotification/{notificationId}")
    ResponseMsg getOneNotification(@PathVariable Integer notificationId){
        System.out.println("用户Id: " + notificationId);
        QueryWrapper<Notifications> wrapper = new QueryWrapper<>();
        wrapper.eq("notification_id", notificationId);
        Notifications notifications = notificationsService.getOne(wrapper);
        if (null == notifications){
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "该通知不存在");
        }
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "查找成功", notifications);
    }

    /**
     * 发送通知给指定用户
     */
    @PostMapping("/notification/send")
    public Map<String, Object> sendNotification(@RequestBody Notifications notification) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = notificationsService.sendNotification(notification);
            result.put("code", success ? 200 : 500);
            result.put("message", success ? "通知发送成功" : "通知发送失败");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "发送失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 发送广播通知
     */
    @PostMapping("/notification/broadcast")
    public Map<String, Object> sendBroadcastNotification(@RequestBody Notifications notification) {
        Map<String, Object> result = new HashMap<>();

        try {
            boolean success = notificationsService.sendBroadcastNotification(notification);
            result.put("code", success ? 200 : 500);
            result.put("message", success ? "广播通知发送成功" : "广播通知发送失败");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "发送失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 标记通知为已读
     */
    @PutMapping("/notification/read/{id}/{userId}")
    public Map<String, Object> markAsRead(@PathVariable Integer id, @PathVariable Integer userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = notificationsService.markAsRead(id, userId);
            result.put("code", success ? 200 : 500);
            result.put("message", success ? "标记成功" : "标记失败");
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "操作失败: " + e.getMessage());
        }

        return result;
    }

    /**
     * 修改 是否已读
     * @param notifications
     * @return
     */
    @RequestMapping("/notification/updateReadType")
    ResponseMsg updateReadType(@RequestBody Notifications notifications){
        UpdateWrapper<Notifications> wrapper = new UpdateWrapper<>();
        wrapper.set(notifications.getIsRead() != null, "is_read", notifications.getIsRead())
                .eq("notification_id", notifications.getNotificationId());
        if (notificationsService.update(wrapper)) {
            return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "修改成功");
        }
        return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "修改失败");
    }
    /**
     * 获取未读通知数量
     */
    @GetMapping("/notification/unread/count")
    public Map<String, Object> getUnreadCount(@RequestParam Integer userId) {
        Map<String, Object> result = new HashMap<>();

        try {
            Integer count = notificationsService.getUnreadCount(userId);
            result.put("code", 200);
            result.put("data", count);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "获取失败: " + e.getMessage());
        }

        return result;
    }
}
